package com.xinzhidi.web.unitconversion.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinzhidi.common.constant.AgreementConstants;
import com.xinzhidi.web.netty.utils.FormatData;
import com.xinzhidi.web.unitconversion.domain.UnitConversion;
import com.xinzhidi.web.unitconversion.mapper.UnitConversionMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;


/**
 * 初始设置Service业务层处理
 *
 * @author cx
 * @date 2023-06-27
 */
@Service
public class UnitConversionService extends ServiceImpl<UnitConversionMapper, UnitConversion> {

    /**
     * 单位转换
     *
     * @param value 值
     * @param code  编码
     * @return 转换后的值
     */
    public String unitConversion(String value, String code, Integer hex) {

        if(StringUtils.isBlank(code)){
            return value;
        }

        if (hex == 0) {
            //十六进制转为十进制
            value = String.valueOf(FormatData.hex2decimal(value));
        }
        LambdaQueryWrapper<UnitConversion> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(UnitConversion::getCode, code)
                .eq(UnitConversion::getDelFlag, AgreementConstants.DEL_FLAG_NO);
        UnitConversion unitConversion = this.getOne(queryWrapper);
        if (unitConversion == null || unitConversion.getPrimaryUnit() == 0) {
            return value;
        }
        value = new BigDecimal(value).multiply(new BigDecimal(unitConversion.getRate())).toString();
        return value;
    }

}
